const { getDbPool } = require('../infra/dbClient');
const db = getDbPool();
const { getLogger } = require('../logger');
const logger = getLogger('models.permissionModel');
const CodeService = require('../services/codeService');
const { isSuperAdminById } = require('../utils/utils');

class PermissionModel {
    // 获取所有权限
    static async getAllPermissions(page = 1, limit = 10, filters = {}, currentUserId = null) {
        const offset = (page - 1) * limit;
        let whereClause = 'WHERE 1=1';
        let params = [];

        // 构建过滤条件
        if (filters.moduleCode) {
            whereClause += ' AND p.module_code = ?';
            params.push(filters.moduleCode);
        }

        if (filters.search) {
            whereClause += ' AND (p.permission_name LIKE ? OR p.permission_code LIKE ?)';
            params.push(`%${filters.search}%`, `%${filters.search}%`);
        }

        if (filters.permission_type !== undefined) {
            whereClause += ' AND p.permission_type = ?';
            params.push(filters.permission_type);
        }

        if (filters.status !== undefined) {
            whereClause += ' AND p.status = ?';
            params.push(filters.status);
        }

        if (filters.is_system !== undefined) {
            whereClause += ' AND p.is_system = ?';
            params.push(filters.is_system);
        }

        // 添加未删除的过滤条件
        whereClause += ' AND p.is_delete = 0';

        const sql = `
      SELECT 
        p.id,
        p.code,
        p.permission_type,
        p.permission_name,
        p.permission_code,
        p.module_code,
        m.name as module_name,
        p.operation_type,
        p.menu_id,
        p.api_path,
        p.api_method,
        p.description,
        p.is_system,
        p.status,
        p.is_delete,
        p.create_by,
        p.update_by,
        creator.name as create_by_name,
        updater.name as update_by_name,
        p.created_at,
        p.updated_at
      FROM permission p
      LEFT JOIN menu m ON m.module_code = p.module_code COLLATE utf8mb4_unicode_ci AND m.is_delete = 0
      LEFT JOIN user creator ON creator.id = p.create_by AND creator.is_delete = 0
      LEFT JOIN user updater ON updater.id = p.update_by AND updater.is_delete = 0
      ${whereClause}
      ORDER BY p.module_code, p.permission_code
        LIMIT ${db.escape(limit)} OFFSET ${db.escape(offset)}
    `;

        try {
            const [rows] = await db.execute(sql, params);
            return rows;
        } catch (error) {
            logger.error('获取所有权限失败', { error });
            throw error;
        }
    }

    // 根据ID获取权限
    static async getPermissionById(id) {
        try {
            const query = 'SELECT id, permission_type, permission_name, permission_code, module_code, operation_type, menu_id, api_path, api_method, description, is_system, status, is_delete, create_by, update_by, created_at, updated_at FROM permission WHERE id = ? AND is_delete = 0';
            const [permissions] = await db.execute(query, [id]);
            return permissions[0] || null;
        } catch (error) {
            logger.error('根据ID获取权限失败', { error, id });
            throw error;
        }
    }

    // 根据角色ID获取权限列表
    static async getPermissionsByRoleId(roleId, currentUserId = null) {
        try {
            const cacheKey = `app:permission:list:role:${roleId}${currentUserId ? `:user:${currentUserId}` : ''}`;

            // 不再使用缓存机制

            // 使用全局方法检查是否是超级管理员
            const isSuperAdmin = currentUserId ? await isSuperAdminById(currentUserId) : false;
            
            let query, params;
            const selectFields = 'p.id, p.permission_type, p.permission_name, p.permission_code, p.module_code, p.operation_type, p.menu_id, p.api_path, p.api_method, p.description, p.is_system, p.status, p.is_delete, p.create_by, p.update_by, p.created_at, p.updated_at';
            
            if (isSuperAdmin) {
                // 超级管理员返回所有权限
                query = `
                    SELECT ${selectFields}
                    FROM permission p
                    WHERE p.is_delete = 0
                    ORDER BY p.module_code, p.permission_code
                `;
                params = [];
            } else {
                // 普通用户查询角色绑定的权限
                query = `
                    SELECT ${selectFields}
                    FROM permission p
                    JOIN role_permission rp ON p.id = rp.permission_id
                    WHERE rp.role_id = ? 
                      AND p.is_delete = 0
                    ORDER BY p.module_code, p.permission_code
                `;
                params = [roleId];
            }

            const [permissions] = await db.execute(query, params);

            // 不再使用缓存机制

            return permissions;
        } catch (error) {
            logger.error('根据角色ID获取权限列表失败', { error, roleId, currentUserId });
            throw error;
        }
    }

    // 根据角色ID获取权限码列表
    static async getPermissionCodesByRoleId(roleId, currentUserId = null) {
        try {
            const cacheKey = `app:permission:codes:role:${roleId}${currentUserId ? `:user:${currentUserId}` : ''}`;

            // 不再使用缓存机制

            // 使用全局方法检查是否是超级管理员
            const isSuperAdmin = currentUserId ? await isSuperAdminById(currentUserId) : false;
            
            let query, params;
            
            if (isSuperAdmin) {
                // 超级管理员拥有所有权限码
                query = `
                    SELECT DISTINCT p.permission_code 
                    FROM permission p
                    WHERE p.is_delete = 0 AND p.status = 1 AND p.permission_code IS NOT NULL
                    ORDER BY p.permission_code
                `;
                params = [];
            } else {
                // 普通用户根据角色获取权限码
                query = `
                    SELECT DISTINCT p.permission_code 
                    FROM permission p
                    JOIN role_permission rp ON p.id = rp.permission_id
                    WHERE rp.role_id = ? 
                      AND p.is_delete = 0 
                      AND p.status = 1
                      AND p.permission_code IS NOT NULL
                    ORDER BY p.permission_code
                `;
                params = [roleId];
            }
            
            const [results] = await db.execute(query, params);
            const permissionCodes = results.map(item => item.permission_code);

            // 不再使用缓存机制

            return permissionCodes;
        } catch (error) {
            logger.error('根据角色ID获取权限码列表失败', { error, roleId, currentUserId });
            throw error;
        }
    }

    // 根据用户ID获取权限码列表
    static async getPermissionCodesByUserId(userId) {
        try {
            const cacheKey = `app:permission:codes:user:${userId}`;

            // 不再使用缓存机制

            // 使用全局方法检查是否是超级管理员
            const isSuperAdmin = await isSuperAdminById(userId);
            
            let query, params;

            
            if (isSuperAdmin) {
                // 超级管理员拥有所有权限码
                query = `
                    SELECT DISTINCT p.permission_code 
                    FROM permission p
                    WHERE p.is_delete = 0 AND p.status = 1 AND p.permission_code IS NOT NULL
                `;
                params = [];
            } else {
                // 普通用户根据角色获取权限码
                query = `
                    SELECT DISTINCT p.permission_code 
                    FROM permission p
                    JOIN role_permission rp ON p.id = rp.permission_id
                    JOIN user_role ur ON rp.role_id = ur.role_id
                    WHERE ur.user_id = ? 
                      AND p.is_delete = 0 
                      AND p.status = 1 
                      AND p.permission_code IS NOT NULL
                `;
                params = [userId];
            }
            
            const [results] = await db.execute(query, params);
            const permissionCodes = results.map(item => item.permission_code);

            // 不再使用缓存机制

            return permissionCodes;
        } catch (error) {
            logger.error('根据用户ID获取权限码列表失败', { error, userId });
            throw error;
        }
    }

    // 检查用户角色是否发生变化
    static async hasUserRoleChanged(userId) {
        try {
            // 不再使用缓存机制
            
            // 获取当前用户角色的哈希值
            const currentQuery = `
                SELECT GROUP_CONCAT(ur.role_id ORDER BY ur.role_id SEPARATOR ',') as role_ids,
                       COUNT(*) as role_count,
                       MAX(ur.updated_at) as latest_update
                FROM user_role ur
                JOIN role r ON ur.role_id = r.id
                WHERE ur.user_id = ? AND  r.is_delete = 0 AND r.status = 1
            `;
            const [currentResult] = await db.execute(currentQuery, [userId]);
            const currentData = currentResult[0];
            
            // 生成当前哈希值
            const currentHash = currentData ? 
                `${currentData.role_ids}_${currentData.role_count}_${currentData.latest_update}` : 
                'empty';
            
            // 如果没有缓存，说明是首次检查，设置缓存并返回false（无变化）
            if (!cachedHash) {
                // 不再使用缓存机制
                return false;
            }
            
            // 比较哈希值
            const hasChanged = cachedHash !== currentHash;
            
            // 如果有变化，更新缓存
            if (hasChanged) {
                // 不再使用缓存机制
            }
            
            return hasChanged;
        } catch (error) {
            logger.error('检查用户角色变化失败', { error, userId });
            throw error;
        }
    }

    // 检查用户角色的权限是否发生变化
    static async hasRolePermissionChanged(userId) {
        try {
            // 不再使用缓存机制
            
            // 获取当前用户权限的哈希值
            const currentQuery = `
                SELECT GROUP_CONCAT(DISTINCT p.id ORDER BY p.id SEPARATOR ',') as permission_ids,
                       COUNT(DISTINCT p.id) as permission_count,
                       MAX(p.updated_at) as latest_permission_update,
                       MAX(rp.updated_at) as latest_role_permission_update
                FROM user_role ur
                JOIN role_permission rp ON ur.role_id = rp.role_id
                JOIN permission p ON rp.permission_id = p.id
                WHERE ur.user_id = ? 

                  AND p.is_delete = 0
                  AND p.status = 1
            `;
            const [currentResult] = await db.execute(currentQuery, [userId]);
            const currentData = currentResult[0];
            
            // 生成当前哈希值
            const currentHash = currentData ? 
                `${currentData.permission_ids}_${currentData.permission_count}_${currentData.latest_permission_update}_${currentData.latest_role_permission_update}` : 
                'empty';
            
            // 如果没有缓存，说明是首次检查，设置缓存并返回false（无变化）
            if (!cachedHash) {
                // 不再使用缓存机制
                return false;
            }
            
            // 比较哈希值
            const hasChanged = cachedHash !== currentHash;
            
            // 如果有变化，更新缓存
            if (hasChanged) {
                // 不再使用缓存机制
            }
            
            return hasChanged;
        } catch (error) {
            logger.error('检查用户权限变化失败', { error, userId });
            throw error;
        }
    }

    // 分配角色权限
    static async assignPermissionsToRole(roleId, permissionIds, currentUserId = null) {
        // 参数验证
        if (!roleId || typeof roleId !== 'number' && typeof roleId !== 'string') {
            throw new Error('角色ID不能为空且必须是有效类型');
        }

        // permissionIds可以为空数组，表示清空角色权限
        if (permissionIds !== undefined && !Array.isArray(permissionIds)) {
            throw new Error('权限ID列表必须是数组类型');
        }

        // 开始事务
        const connection = await db.getConnection();
        try {
            await connection.beginTransaction();

            // 删除原有权限
            await connection.execute('DELETE FROM role_permission WHERE role_id = ?', [roleId]);

            // 插入新权限
            if (permissionIds && permissionIds.length > 0) {
                // 构建IN子句的占位符
                const placeholders = permissionIds.map(() => '?').join(',');
                const query = `
          INSERT INTO role_permission (role_id, permission_id, permission_code, create_by, update_by)
          SELECT ?, p.id, p.permission_code, ?, ? FROM permission p WHERE p.id IN (${placeholders})
        `;
                await connection.execute(query, [roleId, currentUserId, currentUserId, ...permissionIds]);
            }

            await connection.commit();

            // 由于不再使用旧版缓存，所以不再需要清除缓存

            return true;
        } catch (error) {
            await connection.rollback();
            logger.error('分配角色权限失败', { error, roleId, permissionIds });
            throw error;
        } finally {
            connection.release();
        }
    }

    // 更新权限信息
    static async updatePermission(id, updateData, currentUserId = null) {
        const {
            permission_name,
            permission_code,
            module_code,
            permission_type,
            operation_type,
            menu_id,
            api_path,
            api_method,
            description,
            status = 1
        } = updateData;

        // update_by 字段优先使用 updateData 中的值，如果没有则使用 currentUserId
        const update_by = updateData.update_by !== undefined ? updateData.update_by : currentUserId;

        // 查询权限信息（用于检查是否为系统权限）
        const permissionCheckSql = `
      SELECT id, permission_code, code, is_system, is_delete 
      FROM permission 
      WHERE id = ?
    `;
        const [permissionCheckResult] = await db.execute(permissionCheckSql, [id]);
        const permission = permissionCheckResult[0];

        if (!permission) {
            throw new Error('权限不存在');
        }

        // 检查是否已删除
        if (permission.is_delete === 1) {
            throw new Error('权限已删除，无法更新');
        }

        // 如果是系统权限，可能需要额外的权限检查（根据实际需求）
        if (permission.is_system === 1 && currentUserId) {
            // 这里可以添加检查当前用户是否有修改系统权限的权限

        }

        // 如果编码发生了变化，检查新编码是否已被使用
        if (permission_code !== undefined && permission.permission_code !== permission_code) {
            const exists = await this.isCodeExists(permission_code, id);
            if (exists) {
                throw new Error('权限编码已存在');
            }
        }

        // 如果要更新 permission_code，需要检查唯一性
        if (permission_code !== undefined && permission_code !== permission.permission_code) {
            const permissionCodeExists = await this.isPermissionCodeExists(permission_code, id);
            if (permissionCodeExists) {
                throw new Error(`业务权限标识 ${permission_code} 已存在，请更换其他标识`);
            }
        }

        // 如果要更新 code，需要检查唯一性
        if (updateData.code !== undefined && updateData.code !== permission.code) {
            const codeExists = await CodeService.checkCodeExists('PERMISSION_CODE', updateData.code);
            if (codeExists) {
                throw new Error(`权限编码 ${updateData.code} 已存在，请更换其他编码`);
            }
        }

        // 构建更新SQL和参数
        let sql, params;

        // 系统权限和普通权限可以使用相同的更新语句结构
        sql = `
      UPDATE permission 
      SET 
        permission_name = COALESCE(?, permission_name),
        permission_code = COALESCE(?, permission_code),
        module_code = COALESCE(?, module_code),
        permission_type = COALESCE(?, permission_type),
        operation_type = COALESCE(?, operation_type),
        menu_id = ?,
        api_path = ?,
        api_method = ?,
        description = COALESCE(?, description),
        status = COALESCE(?, status),
        update_by = COALESCE(?, update_by),
        updated_at = NOW()
      WHERE id = ?
    `;

        params = [
            permission_name !== undefined ? permission_name : null,
            permission_code !== undefined ? permission_code : null,
            module_code !== undefined ? module_code : null,
            permission_type !== undefined ? permission_type : null,
            operation_type !== undefined ? operation_type : null,
            menu_id !== undefined ? (menu_id || null) : (permission.menu_id || null),
            api_path !== undefined ? (api_path || null) : (permission.api_path || null),
            api_method !== undefined ? (api_method || null) : (permission.api_method || null),
            description !== undefined ? description : null,
            status !== undefined ? status : null,
            update_by !== undefined ? update_by : null,
            id
        ];

        try {
            const [result] = await db.execute(sql, params);

            if (result.affectedRows === 0) {
                throw new Error('权限不存在或更新失败');
            }

            // 由于不再使用旧版缓存，所以不再需要清除缓存

            return result.affectedRows;
        } catch (error) {
            logger.error('更新权限信息失败', { error, id, updateData });
            throw error;
        }
    }

    // 检查业务权限标识是否已存在
    static async isPermissionCodeExists(permissionCode, excludeId = null) {
        try {
            let sql = 'SELECT id FROM permission WHERE permission_code = ? AND is_delete = 0';
            let params = [permissionCode];

            // 如果提供了excludeId，需要排除当前记录
            if (excludeId) {
                sql += ' AND id != ?';
                params.push(excludeId);
            }

            const [rows] = await db.execute(sql, params);
            return rows.length > 0;
        } catch (error) {
            logger.error('检查业务权限标识是否已存在失败', { error, permissionCode, excludeId });
            throw error;
        }
    }

    // 检查权限编码是否已存在（兼容旧代码，内部调用CodeService）
    static async isCodeExists(permissionCode, excludeId = null) {
        try {
            // 检查业务权限标识 permission_code 的唯一性（排除已删除的记录）
            let sql = 'SELECT id FROM permission WHERE permission_code = ? AND is_delete = 0';
            let params = [permissionCode];

            // 如果提供了excludeId，需要排除当前记录
            if (excludeId) {
                sql += ' AND id != ?';
                params.push(excludeId);
            }

            const [rows] = await db.execute(sql, params);

            // 如果找到记录，说明permission_code已存在
            if (rows.length > 0) {
                return true;
            }

            // 同时检查自动生成的code字段（使用CodeService）
            let exists = await CodeService.checkCodeExists('PERMISSION_CODE', permissionCode);

            // 如果CodeService发现存在，但提供了excludeId，我们需要进一步检查是否是要排除的记录
            if (exists && excludeId) {
                const codeCheckSql = 'SELECT id FROM permission WHERE code = ? AND id = ? AND is_delete = 0';
                const [codeRows] = await db.execute(codeCheckSql, [permissionCode, excludeId]);
                // 如果找到的是要排除的记录，则返回false
                if (codeRows.length > 0) {
                    return false;
                }
            }

            return exists;
        } catch (error) {
            logger.error('检查权限编码是否已存在失败', { error, permissionCode, excludeId });
            throw error;
        }
    }

    // 创建新权限
    static async createPermission(permissionData, currentUserId = null) {
        try {
            // 参数验证
            if (!permissionData || typeof permissionData !== 'object') {
                throw new Error('权限数据不能为空且必须是对象类型');
            }

            let { code, permission_type, permission_name, permission_code, module_code, operation_type, menu_id, api_path, api_method, description = '', is_system = 0, status = 1, create_by = currentUserId } = permissionData;

            

            // 验证必填字段
            if (!permission_name) {
                throw new Error('权限名称不能为空');
            }
            if (!permission_code) {
                throw new Error('业务权限标识不能为空');
            }
            if (!module_code) {
                throw new Error('模块编码不能为空');
            }

            // 检查业务权限标识 permission_code 的唯一性（排除已删除的记录）
            const permissionCodeExists = await this.isPermissionCodeExists(permission_code);
            if (permissionCodeExists) {
                logger.error('业务权限标识已存在', { permission_code, permissionName: permission_name });
                throw new Error(`业务权限标识 ${permission_code} 已存在，请更换其他标识`);
            }

            // 如果没有提供code，则自动生成编码（使用generateUniqueCode确保编码唯一）
            if (!code) {
                try {
                    code = await CodeService.generateUniqueCode('PERMISSION_CODE');
                    logger.info('自动生成权限编码', { code, permissionName: permission_name });
                } catch (error) {
                    logger.error('生成权限编码失败', { error, permissionName: permission_name });
                    throw new Error('生成权限编码失败：' + error.message);
                }
            } else {
                // 如果提供了code，则检查编码是否已存在
                const codeExists = await CodeService.checkCodeExists('PERMISSION_CODE', code);
                if (codeExists) {
                    logger.error('权限编码已存在', { code, permissionName: permission_name });
                    throw new Error(`权限编码 ${code} 已存在，请更换其他编码`);
                }
            }

            // 插入新权限
            const insertQuery = `
        INSERT INTO permission (code,permission_type, permission_name, permission_code, module_code, operation_type, menu_id, api_path, api_method, description, is_system, status, create_by)
        VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
      `;

            const params = [
                code,
                permission_type,
                permission_name,
                permission_code,
                module_code,
                operation_type,
                menu_id || null,
                api_path || null,
                api_method || null,
                description,
                is_system,
                status,
                create_by
            ]

            const [result] = await db.execute(insertQuery, params);

            // 由于不再使用旧版缓存，所以不再需要清除缓存

            return result.insertId;
        } catch (error) {
            logger.error('创建新权限失败', { error, permissionData });
            throw error;
        }
    }

    // 根据过滤条件获取权限总数
    static async getPermissionCount(filters = {}) {
        let whereClause = 'WHERE 1=1';
        let params = [];

        // 构建过滤条件
        if (filters.permission_name) {
            whereClause += ' AND permission_name LIKE ?';
            params.push(`%${filters.permission_name}%`);
        }

        if (filters.module_code) {
            whereClause += ' AND module_code = ?';
            params.push(filters.module_code);
        }

        if (filters.permission_code) {
            whereClause += ' AND permission_code LIKE ?';
            params.push(`%${filters.permission_code}%`);
        }

        if (filters.status !== undefined) {
            whereClause += ' AND status = ?';
            params.push(filters.status);
        }

        if (filters.permission_type !== undefined) {
            whereClause += ' AND permission_type = ?';
            params.push(filters.permission_type);
        }

        // 添加未删除的过滤条件
        whereClause += ' AND is_delete = 0';

        const sql = `SELECT COUNT(*) as total FROM permission ${whereClause}`;

        try {
            const [rows] = await db.execute(sql, params);
            return rows[0].total;
        } catch (error) {
            logger.error('获取权限总数失败', { error, filters });
            throw error;
        }
    }

    // 软删除权限
    static async softDeletePermission(id, currentUserId = null) {
        try {
            // 检查权限是否存在且未删除
            const checkSql = 'SELECT id, is_system, is_delete FROM permission WHERE id = ?';
            const [permissions] = await db.execute(checkSql, [id]);
            const permission = permissions[0];

            if (!permission) {
                throw new Error('权限不存在');
            }

            if (permission.is_delete === 1) {
                throw new Error('权限已删除');
            }

            if (permission.is_system === 1) {
                throw new Error('系统权限不能删除');
            }

            // 执行软删除
            const deleteSql = 'UPDATE permission SET is_delete = 1, update_by = ?, updated_at = NOW() WHERE id = ?';
            const [result] = await db.execute(deleteSql, [currentUserId, id]);

            if (result.affectedRows === 0) {
                throw new Error('删除失败');
            }

            // 由于不再使用旧版缓存，所以不再需要清除缓存

            return true;
        } catch (error) {
            logger.error('软删除权限失败', { error, id, currentUserId });
            throw error;
        }
    }

    // 恢复已删除的权限
    static async restorePermission(id, currentUserId = null) {
        try {
            // 检查权限是否存在且已删除
            const checkSql = 'SELECT id, is_delete FROM permission WHERE id = ?';
            const [permissions] = await db.execute(checkSql, [id]);
            const permission = permissions[0];

            if (!permission) {
                throw new Error('权限不存在');
            }

            if (permission.is_delete === 0) {
                throw new Error('权限未删除，无需恢复');
            }

            // 执行恢复
            const restoreSql = 'UPDATE permission SET is_delete = 0, update_by = ?, updated_at = NOW() WHERE id = ?';
            const [result] = await db.execute(restoreSql, [currentUserId, id]);

            if (result.affectedRows === 0) {
                throw new Error('恢复失败');
            }

            // 由于不再使用旧版缓存，所以不再需要清除缓存

            return true;
        } catch (error) {
            logger.error('恢复权限失败', { error, id, currentUserId });
            throw error;
        }
    }

    // 批量软删除权限
    static async batchSoftDeletePermissions(ids, currentUserId = null) {
        // 参数验证
        if (!Array.isArray(ids) || ids.length === 0) {
            throw new Error('权限ID列表不能为空');
        }

        // 验证每个ID
        for (const id of ids) {
            if (!id || isNaN(Number(id))) {
                throw new Error(`无效的权限ID: ${id}`);
            }
        }

        const connection = await db.getConnection();
        try {
            await connection.beginTransaction();

            // 检查所有权限是否存在且可删除
            const placeholders = ids.map(() => '?').join(',');
            const checkSql = `
                SELECT id, is_system, is_delete 
                FROM permission 
                WHERE id IN (${placeholders})
            `;
            const [permissions] = await connection.execute(checkSql, ids);

            if (permissions.length !== ids.length) {
                throw new Error('部分权限不存在');
            }

            // 检查是否有系统权限或已删除的权限
            const systemPermissions = permissions.filter(p => p.is_system === 1);
            const deletedPermissions = permissions.filter(p => p.is_delete === 1);

            if (systemPermissions.length > 0) {
                const systemIds = systemPermissions.map(p => p.id).join(', ');
                throw new Error(`系统权限不能删除: ${systemIds}`);
            }

            if (deletedPermissions.length > 0) {
                const deletedIds = deletedPermissions.map(p => p.id).join(', ');
                throw new Error(`权限已被删除: ${deletedIds}`);
            }

            // 执行批量软删除
            const deleteSql = `
                UPDATE permission 
                SET is_delete = 1, update_by = ?, updated_at = NOW() 
                WHERE id IN (${placeholders})
            `;
            const [result] = await connection.execute(deleteSql, [currentUserId, ...ids]);

            await connection.commit();

            // 由于不再使用旧版缓存，所以不再需要清除缓存

            return {
                success: true,
                deletedCount: result.affectedRows,
                deletedIds: ids
            };
        } catch (error) {
            await connection.rollback();
            logger.error('批量软删除权限失败', { error, ids, currentUserId });
            throw error;
        } finally {
            connection.release();
        }
    }

    // 定期硬删除已软删除的权限（管理员维护功能）
    static async hardDeleteOldPermissions(daysOld = 180, currentUserId = null) {
        try {
            const connection = await db.getConnection();

            try {
                await connection.beginTransaction();

                // 查找指定天数前软删除的权限
                const findSql = `
                    SELECT id, permission_name, permission_code 
                    FROM permission 
                    WHERE is_delete = 1 
                    AND updated_at < DATE_SUB(NOW(), INTERVAL ? DAY)
                `;
                const [oldPermissions] = await connection.execute(findSql, [daysOld]);

                if (oldPermissions.length === 0) {
                    await connection.rollback();
                    return {
                        success: true,
                        deletedCount: 0,
                        message: `没有超过${daysOld}天的已删除权限`
                    };
                }

                // 记录要删除的权限信息
                const deletedIds = oldPermissions.map(p => p.id);
                const deletedInfo = oldPermissions.map(p => `${p.permission_name}(${p.permission_code})`);

                // 先删除相关的角色权限关联
                const deleteRoleMenuSql = `
                    DELETE rm FROM role_menu rm
                    INNER JOIN menu m ON rm.menu_id = m.id
                    WHERE m.permission_code IN (
                        SELECT permission_code FROM permission 
                        WHERE id IN (${deletedIds.map(() => '?').join(',')})
                    )
                `;
                await connection.execute(deleteRoleMenuSql, deletedIds);

                // 硬删除权限记录
                const hardDeleteSql = `
                    DELETE FROM permission 
                    WHERE id IN (${deletedIds.map(() => '?').join(',')})
                `;
                const [result] = await connection.execute(hardDeleteSql, deletedIds);

                await connection.commit();

                // 记录清理日志
                logger.info('定期硬删除权限完成', {
                    deletedCount: result.affectedRows,
                    daysOld,
                    currentUserId,
                    deletedPermissions: deletedInfo
                });

                // 由于不再使用旧版缓存，所以不再需要清除缓存

                return {
                    success: true,
                    deletedCount: result.affectedRows,
                    deletedIds,
                    deletedInfo,
                    message: `成功清理${result.affectedRows}个超过${daysOld}天的已删除权限`
                };

            } catch (error) {
                await connection.rollback();
                throw error;
            } finally {
                connection.release();
            }

        } catch (error) {
            logger.error('定期硬删除权限失败', { error, daysOld, currentUserId });
            throw error;
        }
    }

    // 批量恢复已删除的权限
    static async batchRestorePermissions(ids, currentUserId = null) {
        // 参数验证
        if (!Array.isArray(ids) || ids.length === 0) {
            throw new Error('权限ID列表不能为空');
        }

        // 验证每个ID
        for (const id of ids) {
            if (!id || isNaN(Number(id))) {
                throw new Error(`无效的权限ID: ${id}`);
            }
        }

        const connection = await db.getConnection();
        try {
            await connection.beginTransaction();

            // 检查所有权限是否存在且已删除
            const placeholders = ids.map(() => '?').join(',');
            const checkSql = `
                SELECT id, is_delete 
                FROM permission 
                WHERE id IN (${placeholders})
            `;
            const [permissions] = await connection.execute(checkSql, ids);

            if (permissions.length !== ids.length) {
                throw new Error('部分权限不存在');
            }

            // 检查是否有未删除的权限
            const activePermissions = permissions.filter(p => p.is_delete === 0);
            if (activePermissions.length > 0) {
                const activeIds = activePermissions.map(p => p.id).join(', ');
                throw new Error(`权限未被删除，无需恢复: ${activeIds}`);
            }

            // 执行批量恢复
            const restoreSql = `
                UPDATE permission 
                SET is_delete = 0, update_by = ?, updated_at = NOW() 
                WHERE id IN (${placeholders})
            `;
            const [result] = await connection.execute(restoreSql, [currentUserId, ...ids]);

            await connection.commit();

            // 由于不再使用旧版缓存，所以不再需要清除缓存

            return {
                success: true,
                restoredCount: result.affectedRows,
                restoredIds: ids
            };
        } catch (error) {
            await connection.rollback();
            logger.error('批量恢复权限失败', { error, ids, currentUserId });
            throw error;
        } finally {
            connection.release();
        }
    }

    // 移除角色的所有权限绑定
    static async removeAllPermissionsFromRole(roleId, currentUserId = null) {
        try {
            if (!roleId || isNaN(Number(roleId))) {
                throw new Error('角色ID格式错误');
            }

            // 物理删除角色权限关联记录
            const sql = `
                DELETE FROM role_permission 
                WHERE role_id = ?
            `;
            
            const [result] = await db.execute(sql, [roleId]);
            
            logger.info('移除角色所有权限绑定', { roleId, affectedRows: result.affectedRows, currentUserId });
            
            // 由于不再使用旧版缓存，所以不再需要清除缓存
            
            return result.affectedRows;
        } catch (error) {
            logger.error('移除角色所有权限绑定失败', { error, roleId, currentUserId });
            throw error;
        }
    }

    // 清除权限缓存
    // 清除权限缓存功能已移除，不再使用旧版缓存

    // 获取已删除的权限列表（管理员功能）
    static async getDeletedPermissions(page = 1, limit = 10, filters = {}) {
        try {
            const offset = (page - 1) * limit;
            let whereClause = 'WHERE is_delete = 1';
            let params = [];

            // 构建过滤条件
            if (filters.moduleCode) {
                whereClause += ' AND module_code = ?';
                params.push(filters.moduleCode);
            }

            if (filters.search) {
                whereClause += ' AND (permission_name LIKE ? OR permission_code LIKE ?)';
                params.push(`%${filters.search}%`, `%${filters.search}%`);
            }

            const sql = `
        SELECT 
          id,
          code,
          permission_type,
          permission_name,
          permission_code,
          module_code,
          operation_type,
          menu_id,
          api_path,
          api_method,
          description,
          is_system,
          status,
          is_delete,
          create_by,
          update_by,
          created_at,
          updated_at,
          DATEDIFF(NOW(), updated_at) as days_deleted
        FROM permission
        ${whereClause}
        ORDER BY updated_at DESC
        LIMIT ${Number(limit)} OFFSET ${Number(offset)}
      `;

            const [permissions] = await db.execute(sql, params);

            // 获取总数
            const countSql = `SELECT COUNT(*) as total FROM permission ${whereClause}`;
            const [countResult] = await db.execute(countSql, params);
            const total = countResult[0].total;

            return {
                permissions,
                pagination: {
                    page: Number(page),
                    limit: Number(limit),
                    total,
                    totalPages: Math.ceil(total / limit)
                }
            };
        } catch (error) {
            logger.error('获取已删除权限列表失败', { error, page, limit, filters });
            throw error;
        }
    }
}

module.exports = PermissionModel;